package com.lkc.controller;

import com.lkc.bean.Users;
import com.lkc.mapper.UsersDao;
import com.lkc.service.LoginService;
import com.lkc.util.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/login")
@CrossOrigin
public class LoginController {
    @Autowired
    LoginService loginService;

    // 添加 UsersDao 的注入
    @Autowired
    private UsersDao usersDao;

    @GetMapping("/captcha")
    public Result captcha() {
        return Result.success(CaptchaUtil.getCaptcha());
    }

    @PostMapping("/dologin")
    public Result login(Users user, @RequestParam("captcha") String captcha,@RequestParam("key") String key) {
        //验证码验证
        if (!CaptchaUtil.checkCaptcha(key, captcha)){
            return Result. fail(500,"验证码错误");
        }
        //登录
        try {

            String token= loginService.login(user);
            //删除掉验证码
            return Result.success("登录成功",token);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(500, e.getMessage());
        }
    }

    @GetMapping("/logininfo")
    public Result logininfo(HttpServletRequest  request, HttpSession  session){
        String token=request.getHeader(SYS.TOKEN_AUTHORIZATION);
        Users user= loginService.logininfo(token);
        return Result.success(user);
    }

    //  邮箱验证修改密码
    @PostMapping("/sendEmailCode")
    public Result sendEmailCode(@RequestBody Users user) {
        try {
            // 1. 查询数据库中用户名对应的用户信息
            Users result = usersDao.getByusername(user.getUsername());
            if (result == null) {
                return Result.fail(500, "用户不存在");
            }

            // 2. 检查邮箱是否存在
            if (result.getEmail() == null || result.getEmail().isEmpty()) {
                return Result.fail(500, "用户未绑定邮箱，请联系管理员");
            }

            // 3. 生成验证码 (6位数字)
            String code = String.format("%06d", new Random().nextInt(999999));

            // 4. 保存验证码到缓存 (这里使用 ExpiryMap)
            CaptchaUtil.getExpiryMap().put("email_code_" + result.getEmail(), code, 1000 * 60 * 5); // 5分钟有效

            // 5. 发送邮件
            EmailUtil.sendEmail(result.getEmail(), code);

            return Result.success("验证码已发送至您的邮箱");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(500, "发送失败: " + e.getMessage());
        }
    }

    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestBody Map<String, String> params) {
        try {
            String username = params.get("username");
            String emailCode = params.get("emailCode");
            String newPassword = params.get("newPassword");

            // 1. 查询用户信息
            Users user = usersDao.getByusername(username);
            if (user == null) {
                return Result.fail(500, "用户不存在");
            }

            // 2. 验证邮箱验证码
            String key = "email_code_" + user.getEmail();
            String cachedCode = (String) CaptchaUtil.getExpiryMap().get(key);
            if (cachedCode == null || !cachedCode.equals(emailCode)) {
                return Result.fail(402, "验证码错误或已过期");
            }

            // 3. 更新密码（需要加密处理）
            user.setPassword(PasswordUtil.getEncryption(newPassword));
            usersDao.edit(user);

            // 4. 删除已使用的验证码
            CaptchaUtil.getExpiryMap().remove(key);

            return Result.success("密码重置成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(500, "重置失败: " + e.getMessage());
        }
    }
}

